<?php

namespace App\Models\Report;

use App\Models\Company\BalanceSheet;
use App\Models\Company\Company;
use App\Models\FinancialBasis\BalanceItem;

class BalanceList
{
    //键名为年份，键值为 Balance
    public $balance_list = [];

    //公司代码
    public $company_code;
    //数组格式， 2个键值，起始 和 结束
    public $year = ['start' => 0, 'end' => 0];

    //报表范围
    public $report_range_id = 2;
    //报表类型
    public $report_categor_id = 4;

    //本公司有的资产负债表项目
    public $balance_items;

    public function __construct(string $company_code, array $year, int $report_range_id, int $report_category_id = 4)
    {
        $this->company_code = $company_code;
        $this->year['start'] = $year['start'];
        $this->year['end'] = $year['end'];
        $this->report_range_id = $report_range_id;
        $this->report_category_id = $report_category_id;
        $this->init();
    }

    private function init()
    {
        $balance_sheets = BalanceSheet::where([
            'company_code' => $this->company_code,
            'report_range_id' => $this->report_range_id,
            'report_category_id' => $this->report_category_id,
        ])->whereBetween('year', [$this->year['start'], $this->year['end']])->get();

        for ($i = $this->year['start']; $i <= $this->year['end']; $i++) {
            $balance = new Balance($this->company_code, $i, $this->report_category_id, $this->report_range_id);
            $this->balance_list[$i] = $balance;
        }

        $this->assignBalanceSheet($balance_sheets);
        $this->setBalanceItems($this->company_code);
    }

    //分配资产负债表明细
    private function assignBalanceSheet($balance_sheets)
    {
        foreach ($balance_sheets as $balance_sheet) {
            $this->balance_list[$balance_sheet->year]->addSheet($balance_sheet);
        }
    }

    public function getItem(int $year, int $balance_item_id)
    {
        // dd($this->balance_list[$year]);
        return $this->balance_list[$year]->getItem($balance_item_id) ? $this->balance_list[$year]->getItem($balance_item_id) : '';
    }

    //设置只有本公司有的资产负债表列项目
    private function setBalanceItems(string $company_code)
    {
        //获取所有的资产负债表列项
        $balance_items = (new BalanceItem())->getSort(['company_code' => $company_code]);

        $this->balance_items = $balance_items;
    }


    public function company(): Company
    {
        $model = Company::where(['code' => $this->company_code])->first();
        return $model;
    }
}
